import axios from 'axios'
import {message} from 'ant-design-vue'
import CONSTANT from './constant'

const service = axios.create({
  baseURL: process.env["VUE_APP_BASE_URL"],
  timeout: 30000
})

service.interceptors.request.use(config => {
  if (localStorage.getItem("token")) {
    let token = JSON.parse(localStorage.getItem("token"))
    config.headers[token.tokenName] = token.tokenValue
  }
  return config
}, err => {
  return Promise.reject(err)
})

service.interceptors.response.use(resp => {
  if (resp.data.code !== CONSTANT.RESP.SUCCESS) {
    // 抛出业务异常
    if (resp.data.code === CONSTANT.RESP.NOT_LOGIN) {
      message.info('请重新登录')
      localStorage.removeItem('token')
      this.$router.push('/login').then(() => {})
    }
    return Promise.reject(resp)
  }
  return resp
}, err => {
  // 非业务异常，响应异常
  message.error('服务异常，请联系管理员')
  return Promise.reject(err)
})

export default service